package org.example.https;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author hh
 * @since 2024/11/2
 */
public class NettyEchoServer {

    ServerBootstrap b = new ServerBootstrap();

    public static void main(String[] args) {
        NettyEchoServer nettyEchoServer = new NettyEchoServer();
        nettyEchoServer.runServer(9999);
    }

    public void runServer(int port) {
        // 创建反应器轮询组
        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            // 设置反应器轮询组
            b.group(bossLoopGroup, workerLoopGroup);
            // 设置 NIO类型的通道
            b.channel(NioServerSocketChannel.class);
            // 设置监听端口
            b.localAddress(port);
            // 设置通道的参数
            b.option(ChannelOption.SO_KEEPALIVE, true);
            // 装配子通道流水线
            b.childHandler(new HttpsServerInitializer());
            // 开始绑定服务器
            // 通过调用 sync同步方法阻塞直到绑定成功
            ChannelFuture channelFuture = b.bind().sync();
            System.out.println("服务器启动成功，监听端口：" + channelFuture.channel().localAddress());
            // 等待通道关闭的异步任务结束
            // 服务监听通道会一直等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            // 优雅关闭EventLoopGroup
            // 释放掉所有资源，包括创建的线程
            workerLoopGroup.shutdownGracefully();
            bossLoopGroup.shutdownGracefully();
        }
    }
}
